﻿using SoldiHive.Infrustructure.Extensions;
using System;
using System.Collections.Generic;
using System.Text;

namespace SoldiHive.Model
{
	[Serializable]
	public class Rating : IFormattable
	{
		public const double MaxRate = 10;

		public Rating()
		{

		}

		public Rating(Site source)
		{
			this.Source = source;
		}

		public Site Source { get; set; }
		public double? Rate { get; set; }
		public double? PriceTarget { get; set; }

		public static Rating Empty
		{
			get
			{
				return new Rating()
				{
					Rate = null,
					PriceTarget = null
				};
			}
		}

		public override string ToString()
		{
			return this.ToString("Source,Rate", null);
		}

		public string ToString(string format, IFormatProvider formatProvider)
		{
			if (string.IsNullOrEmpty(format))
			{
				format = "Source,Rate";
			}

			var ratingStringBuilder = new StringBuilder();

			var propertyNames = format.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
			foreach (var propertyName in propertyNames)
			{
				var propertyValue = string.Empty;
				if (propertyName.Equals("Source", StringComparison.InvariantCultureIgnoreCase))
				{
					ratingStringBuilder.Append(this.Source.GetDescription());
					ratingStringBuilder.Append(":");
				}
				else if (propertyName.Equals("Rate", StringComparison.InvariantCultureIgnoreCase))
				{
					if (this.Rate.HasValue)
					{
						ratingStringBuilder.Append(string.Format("{0:0.0}", this.Rate));
					}
					else
					{
						ratingStringBuilder.Append("N/A");
					}
				}
				else
				{
					if (this.PriceTarget.HasValue)
					{
						if (ratingStringBuilder.Length > 0)
						{
							ratingStringBuilder.Append(" ");
						}

						ratingStringBuilder.Append(string.Format("${0:0.##}", this.PriceTarget).Align(7));
					}
					else
					{
						ratingStringBuilder.Append("N/A");
					}
				}
			}

			var ratingString = ratingStringBuilder.ToString();

			return ratingString;
		}
	}
}
